<?php

// 作者：行者  i126@126.com  2018-9-11
// 使用请保留此信息

//function api_json_insert_to_db($url,$tablename,$isDup,$DupName){

// =====自动建表开始=====
$tmp_con=array();
$tmp_con=get_data($url);
$tmp_arr=json_decode($tmp_con,true);

$arr = array_map('array_shift',$tmp_arr);
$arr = $arr['data'];
$single_arr=fixedArray($arr);

$tmp_sql = 'DROP TABLE IF EXISTS `'.$tablename.'`;';
$tmp_sql.= 'CREATE TABLE `'.$tablename.'` (';
$tmp_sql.= '`bid` int(11) NOT NULL AUTO_INCREMENT, ';
foreach($single_arr as $key => $value){
    if(!is_numeric($key)){
      $tmp_sql.= '`'.$key.'` varchar('.(strlen($value)*2).') DEFAULT NULL, ';
    }
}
$tmp_sql.= 'PRIMARY KEY (`bid`) ';
$tmp_sql.= ') ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;';

if (mysqli_multi_query($conn,$tmp_sql))
{
      do
      {
         if ($result=mysqli_store_result($conn))
         {
           while ($row=mysqli_fetch_row($result))
           { }
           mysqli_free_result($result);
         }
      }while (mysqli_next_result($conn));
}
// =====自动建表结束=====

//print_r('自动建表完成<br>');

$sql="call TBL('{$tablename}',$isDup,'{$DupName}')";
// 使用存储过程执行多个 SQL 语句 时必须用以下方法，否则会出现2014错误
if (mysqli_multi_query($conn,$sql))
{
    do
    {
        // 存储第一个结果集
        if ($result=mysqli_store_result($conn))
        {
            while ($row=mysqli_fetch_row($result))
            {
                //是否排重,值为0或需排重字段名
                $isDuplicate       = $row[0];  //isDuplicate
                //从临时表读入数据并插入原始表，且自动排重SQL
                $insert_kv_sql     = $row[1];  //insert_kv_sql
                //构建临时表SQL
                $tb_kv_tmptbl      = $row[2];  //tb_kv_tmptbl
                //将数据插入临时表
                $insert_tmptbl_sql = $row[3];  //insert_tmptbl_sql
                //字段表
                $tb_flds           = $row[4];  //tb_flds
                //字段类型表
                $tb_types          = $row[5];  //tb_types
                //字段变量表
                $tb_vars           = $row[6];  //tb_vars
                //字段值变量表
                $tb_values         = $row[7];  //tb_values
                //表检索SQL
                $select_sql        = $row[8];  //select_sql
                //将数据插入原始表，不排重
                $insert_sql        = $row[9];  //insert_sql
            }
            mysqli_free_result($result);
        }
    }
    while (mysqli_next_result($conn));
}

//print_r('调用存储过程初始化完成<br>');

//   =====创建临时表开始=====
if($isDup){
   $sql=$tb_kv_tmptbl;
   $sql = str_replace(',lock',',`lock`',$sql);

   if (mysqli_multi_query($conn,$sql))
   {
      do
      {
         if ($result=mysqli_store_result($conn))
         {
           while ($row=mysqli_fetch_row($result))
           { }
           mysqli_free_result($result);
         }
      }while (mysqli_next_result($conn));
   }
}
//   =====创建临时表结束=====

//print_r('创建临时表完成<br>');

$content=array();
$content=get_data($url);
$tmp=json_decode($content,true);

$tmp_size=array_get_by_key($tmp, 'size',0);
if(empty($tmp_size)){
  $tmp_size=count($tmp['data']);
}


$rs_flds_num = substr_count($tb_flds, ',');  //字段数量
$rs_flds_arr = explode(',', $tb_flds);       //字段名转数组

for($i=0;$i<$tmp_size;$i++){

  if($isDup){
     //数据存入临时表
     $sql = $insert_tmptbl_sql; 
  }else{
     $sql = $insert_sql;
  }  
  $my_tb_values = $tb_values;
  for ($j=0;$j<=$rs_flds_num;$j++) {
     $flds_name  = $rs_flds_arr[$j];
     $my_flds_var    = "\$" . $flds_name;
     $my_flds_var_replace = '{' . $my_flds_var . '}';
     ${$my_flds_var} = array_get_by_key($tmp, $flds_name,$i);  
     $str_flds_value = str_replace($my_flds_var_replace, ${$my_flds_var}, $my_tb_values);
     $my_tb_values = $str_flds_value;  
  }
  $preg= '/values([\s\S]*)/i';
  preg_match_all($preg,$sql,$res);
  $sql=str_replace($res[0][0],' values('.$str_flds_value.')',$sql);
  $sql = str_replace(',lock',',`lock`',$sql);
  
  //echo $sql;
  //exit;
   
  $obj = mysqli_query($conn, $sql);
}

//print_r('数据抓取并存入内存临时表完成<br>');

//将临时表中数据导入原始表，并排重
if($isDup){
  $sql=$insert_kv_sql;
  $sql = str_replace(',lock',',`lock`',$sql);
  $obj = mysqli_query($conn, $sql);
}
//关闭数据库连接
mysqli_close($conn);

//print_r('数据存入正式表完成<br><br><br>');

//print_r('=== 谢谢您的使用 ===<br><br><br>');
//return true;
//}
?> 